package org.aurora.core.biz.config.jdbc;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import javax.sql.DataSource;


@Configuration
@EnableConfigurationProperties(JdbcProperties.class)
@PropertySource(value = "classpath:biz/jdbc.properties")
public class JdbcConfiguration {
    private static final Logger log = LoggerFactory.getLogger(JdbcConfiguration.class);
    @Bean
    public DataSource dataSource(@Autowired JdbcProperties jdbcProperties) {
        try {
            DruidDataSource dataSource = new DruidDataSource();
            dataSource.setDriverClassName(jdbcProperties.getDriverClassName());
            dataSource.setUrl(jdbcProperties.getUrl());
            dataSource.setUsername(jdbcProperties.getUsername());
            dataSource.setPassword(jdbcProperties.getPassword());
            return dataSource;
        } catch (Exception e) {
            log.error("Failed to create datasource", e);
            throw e;
        }
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(@Autowired DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);

        // 获取默认配置并修改
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setMapUnderscoreToCamelCase(true);
        sessionFactory.setConfiguration(configuration);

        return sessionFactory.getObject();
    }
}
